package com.shujia.day17;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Demo04GetMethod {
    public static void main(String[] args) throws ClassNotFoundException, InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchFieldException {
        Class<?> teacherClazz = Class.forName("com.shujia.day17.Teacher");

        // 获取无参构造的对象
        Constructor<?> declaredConstructor = teacherClazz.getDeclaredConstructors()[0];
        declaredConstructor.setAccessible(true);
        Teacher teacher = (Teacher)declaredConstructor.newInstance();

        Field name = teacherClazz.getField("name");
        name.set(teacher,"AI Teacher");
        System.out.println(teacher);

        // TODO 获取方法

        for (Method method : teacherClazz.getMethods()) {
            System.out.println(method);
        }

        Method[] declaredMethods = teacherClazz.getDeclaredMethods();
        for (Method declaredMethod : declaredMethods) {
            System.out.println(declaredMethod);
        }

        // 执行方法
        Method declaredMethod = declaredMethods[2];
        System.out.println("当前方法："+declaredMethod);
        declaredMethod.setAccessible(true);
        declaredMethod.invoke(teacher);

        // 执行有参的方法
        Method declaredMethod1 = declaredMethods[1];
        declaredMethod1.setAccessible(true);
        declaredMethod1.invoke(teacher,"大数据");

        Method declaredMethod2 = declaredMethods[0];
        declaredMethod2.setAccessible(true);
        String teacher2String = (String)declaredMethod2.invoke(teacher);
        System.out.println(teacher2String);

    }
}
